<template>
  <a-modal title-align="start" :title="props.type == 'add' ? '新增店铺' : '编辑店铺'" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="600">
    <a-form auto-label-width ref="formRef" size="medium" :model="form">
      <!-- <a-form-item label="店铺ID">
        <a-input v-model.trim="form.shopId" placeholder="请输入店铺ID" allow-clear />
      </a-form-item> -->
      <a-form-item field="shopName" label="店铺名称" :rules="rules.shopName">
        <a-input v-model="form.shopName" placeholder="请输入店铺名称" allow-clear />
      </a-form-item>
      <a-form-item field="wooCommerceUrl" label="网站域名" :rules="rules.wooCommerceUrl">
        <a-input v-model="form.wooCommerceUrl" placeholder="请输入网站域名" allow-clear />
      </a-form-item>
      <a-form-item label="店铺授权key">
        <a-input v-model="form.wooCommerceAuthKey" placeholder="请输入店铺授权key" allow-clear />
      </a-form-item>
      <a-form-item label="店铺授权密码">
        <a-input v-model="form.wooCommerceAuthPwd" placeholder="请输入店铺授权密码" allow-clear />
      </a-form-item>
      <a-form-item label="品牌">
        <a-select v-model="form.brandIdList" placeholder="请选择品牌" :max-tag-count="2" multiple allow-search allow-clear>
          <a-option :value="item.id" v-for="(item, index) of brandList" :key="index">{{ item.name }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="shopManager" label="店长" :rules="rules.shopManager">
        <a-select v-model="form.shopManager" placeholder="请选择店长" allow-search allow-clear>
          <a-option :value="item.id" v-for="(item, index) of userList" :key="index">{{ item.userName }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="店员">
        <a-select v-model="form.shopClerkIds" :max-tag-count="2" placeholder="请选择店员" multiple allow-search allow-clear>
          <a-option :value="item.id" v-for="(item, index) of userList" :key="index">{{ item.userName }}</a-option>
        </a-select>
      </a-form-item>
    </a-form>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="loading" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { defineComponent, ref, computed, onMounted } from 'vue'
  import { getBrandList } from '@/api/product'
  import { getOrganizesUser, createShop, updateShopBase, getShopInfo, updateShopMarketBatch } from '@/api/system'
  import { Message } from '@arco-design/web-vue'
  let props = defineProps(['modelValue', 'type', 'info'])
  let emits = defineEmits(['save', 'update:modelValue'])
  const formRef = ref()
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  let loading = ref(false)
  let form: any = ref({
    // shopId: '',
    shopName: '',
    wooCommerceUrl: '',
    wooCommerceAuthKey: '',
    wooCommerceAuthPwd: '',
    brandIdList: [],
    shopManager: '',
    shopClerkIds: [],
  })
  let brandList: any = ref([])
  let userList: any = ref([])
  let rules = ref({
    shopName: [{ required: true, message: '请输入店铺名称' }],
    wooCommerceUrl: [{ required: true, message: '请输入网站域名' }],
    shopManager: [{ required: true, message: '请选择店长' }],
  })

  const getBrand = async () => {
    const res: any = await getBrandList({ pageSize: 999999 })
    brandList.value = res.data?.records || []
  }
  // 获取用户列表
  const getUSerList = async () => {
    let params = {
      depart: false,
      pageNum: 1,
      pageSize: 1000,
    }
    const res: any = await getOrganizesUser(params)
    if (res) {
      userList.value = res.data.records
    }
  }

  const submit = async () => {
    const valid = await formRef.value.validate()
    if (valid) return
    let params: any = {
      platform: 'wooCommerce',
      wooCommerceOpen: true,
      ...form.value,
      shopMasterIds: [form.value.shopManager],
      // 默认美国站点
      marketplaceIds: ['ATVPDKIKX0DER'],
      region: '北美地区',
    }
    // 品牌处理
    if (params.brandIdList[0]) {
      params.brandIdList.forEach((e: any) => {
        let brandInfo = brandList.value.find((el: any) => el.id == e)
        let obj = {
          brandCode: brandInfo?.code,
          brandId: brandInfo?.id,
          brandName: brandInfo?.name,
        }
        if (!params.shopBrandParams) params.shopBrandParams = []
        params.shopBrandParams.push(obj)
      })
    }
    let res: any = null
    try {
      loading.value = true
      if (props.type == 'add') {
        res = await createShop(params)
        if (res) {
          let addshopClerkParams = {
            ...params,
            clerkType: 2,
            idList: [res.data],
            shopClerkIds: form.value.shopClerkIds,
            status: 1,
          }
          await updateShopBase(addshopClerkParams)
        }
      } else {
        params.idList = [params.id]
        res = await updateShopBase(params)
        setShopClerk()
      }
      if (res) {
        Message.success(props.type == 'add' ? '新增成功' : '编辑成功')
        emits('save')
        showvisible.value = false
      }
    } catch (error) {}
    loading.value = false

    // showvisible.value = false
  }

  const setShopClerk = async () => {
    console.log(props.info)
    let arr = props.info?.shopMarkets || []
    let item = arr.find((e) => e.marketplaceId == 'ATVPDKIKX0DER')
    let params = {
      clerkType: 2,
      idList: [item?.id || ''],
      shopClerkIds: form.value.shopClerkIds,
    }
    const res = await updateShopMarketBatch(params)
  }

  const init = async () => {
    const res: any = await getShopInfo({ id: props.info.id })
    console.log(res)
    form.value = res.data || {}
    form.value.shopManager = form.value.shopMasters[0]?.userId
    // 品牌回显
    let brands = form.value.shopBrands || []
    form.value.brandIdList = brands.map((e: any) => e.brandId)
    // 店员回显
    let shopManagers = form.value.shopMarkets[0]?.shopClerks || []
    form.value.shopClerkIds = shopManagers.map((e: any) => e.userId)
  }

  onMounted(() => {
    getBrand()
    getUSerList()
    if (props.type == 'edit') init()
  })
</script>

<style lang="less" scoped></style>
